<script setup>
import { ref, onMounted } from 'vue'
import useTableView from '@/hooks/use-table-view'
import useDelPop from '@/hooks/use-del-popover'
import DialogMenuPermit from '@/views/system/menu-permit/components/DialogMenuPermit.vue'
import { cloneDeep } from 'lodash-es'
import { delMenuPermitMockApi, treeMenuPermitMockApi } from '@/api/mock-js/system/menu-permit-api'
import { listParamsByKeyMockApi } from '@/api/mock-js/system/params-api'

defineOptions({
  name: 'MenuPermit'
})
const queryInfo = ref({params: {}})
const {tableData, loading, dialogRef, showDialog, visibleDialog} = useTableView(queryInfo)
// 删除 hooks
const {delData, visibleDelPop, tempRef, showDelPop} = useDelPop()

// 获取所有类型为MENU的列表，用于弹窗里分配‘上级菜单’
const menuList = ref([])
const renderTable = async () => {
  try {
    const res = await treeMenuPermitMockApi()
    tableData.value = res.data
    let target = cloneDeep(res.data)
    await recursiveMenuList(target)
    menuList.value = [{
      id: 0,
      disabled: false,
      permissionName: '无上级菜单'
    }, ...target]
  } catch (e) {
  }
}
// 递归删除 menu里的BUTTON项
const recursiveMenuList = (target) => {
  for (let i = 0; i < target.length; i++) {
    target[i].disabled = false
    if (target[i].permissionType === 'BUTTON') {
      // 删除类型的BUTTON
      target.splice(i, 1)
      i--
    } else {
      if (target[i]?.children?.length) {
        recursiveMenuList(target[i].children)
      }
    }
  }
}
// 删除row
const del = async () => {
  loading.value = true
  try {
    await delMenuPermitMockApi(delData.value.id)
    await renderTable()
  } catch (e) {
    throw new Error(e)
  } finally {
    loading.value = false
  }
}
// 获取权限类型
const permissionTypeList = ref([])
const getPermissionTypeList = async () => {
  try {
    const res = await listParamsByKeyMockApi( 'permissionType')
    permissionTypeList.value = res.data
  } catch (e) {
  } finally {
  }
}
// 添加子级
const addChild = (row) => {
  visibleDialog.value = true
  nextTick(() => {
    dialogRef.value.title = `${row.permissionName}-添加子级`
    dialogRef.value.childFlag = true
    dialogRef.value.formData.parentId = row.id
    dialogRef.value?.setInitData()
  })
}
onMounted(async () => {
  await Promise.all([
    getPermissionTypeList(),
    renderTable()
  ])
})

let pageData = {
  list: [
    {
      id: 3,
      permissionName: '系统管理',
      permissionType: 'MENU',
      parentId: 0,
      sort: 2,
      permissionKey: null,
      permissionPath: '/system',
      permissionTopPath: null,
      icon: null,
      children: [
        {
          id: 5,
          permissionName: '用户管理',
          permissionType: 'MENU',
          parentId: 3,
          sort: 1,
          permissionKey: null,
          permissionPath: '/user',
          permissionTopPath: '/system',
          icon: 'User',
          children: null
        },
        {
          id: 4,
          permissionName: '角色管理',
          permissionType: 'MENU',
          parentId: 3,
          sort: 2,
          permissionKey: null,
          permissionPath: '/role',
          permissionTopPath: '/system',
          icon: 'Key',
          children: null
        },
        {
          id: 6,
          permissionName: '菜单与权限',
          permissionType: 'MENU',
          parentId: 3,
          sort: 3,
          permissionKey: null,
          permissionPath: '/menuPermit',
          permissionTopPath: '/system',
          icon: null,
          children: null
        },
        {
          id: 7,
          permissionName: '系统字典',
          permissionType: 'MENU',
          parentId: 3,
          sort: 4,
          permissionKey: null,
          permissionPath: '/params',
          permissionTopPath: '/system',
          icon: 'Collection',
          children: [
            {
              id: 8,
              permissionName: '编辑按钮',
              permissionType: 'BUTTON',
              parentId: 7,
              sort: null,
              permissionKey: 'sys:params:edit',
              permissionPath: null,
              permissionTopPath: null,
              icon: null,
              children: null
            },
            {
              id: 9,
              permissionName: '删除按钮',
              permissionType: 'BUTTON',
              parentId: 7,
              sort: null,
              permissionKey: 'sys:params:del',
              permissionPath: null,
              permissionTopPath: null,
              icon: null,
              children: null
            }
          ]
        }
      ]
    },
    {
      id: 17,
      permissionName: '广场',
      permissionType: 'MENU',
      parentId: 0,
      sort: 100,
      permissionKey: null,
      permissionPath: '/playground',
      permissionTopPath: null,
      icon: null,
      children: [
        {
          id: 18,
          permissionName: '测试模块',
          permissionType: 'MENU',
          parentId: 17,
          sort: 1,
          permissionKey: null,
          permissionPath: '/testView',
          permissionTopPath: '/playground',
          icon: null,
          children: [
            {
              id: 35,
              permissionName: '你好',
              permissionType: 'BUTTON',
              parentId: 18,
              sort: null,
              permissionKey: ':tset:btn',
              permissionPath: null,
              permissionTopPath: null,
              icon: null,
              children: null
            },
            {
              id: 19,
              permissionName: '测试表单',
              permissionType: 'MENU',
              parentId: 18,
              sort: 3,
              permissionKey: null,
              permissionPath: '/testView/formTest',
              permissionTopPath: '/playground',
              icon: 'isForm',
              children: null
            }
          ]
        }
      ]
    }
  ]
}
</script>

<template>
  <TableView class="permit" v-loading="loading" :show-page="false" @reload-table="renderTable">
    <template #headerRight>
      <ElButton type="primary" @click="showDialog()">添加菜单/权限</ElButton>
    </template>
    <ElTable :data="tableData" ref="tableRef" v-loading="loading" style="width: 100%;" row-key="id" border lazy
             :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <ElTableColumn prop="permissionName" label="菜单/权限名" width="220"/>
      <ElTableColumn prop="sort" label="排序" min-width="80" align="center"/>
      <ElTableColumn label="菜单类型" min-width="100" align="center" #default="{ row }">
        <template v-for="{paramValue,paramValueName} in permissionTypeList" :key="paramValue">
          <ElTag :type="row.permissionType === 'MENU' ? 'success' : ''" v-if="row.permissionType ===paramValue"
          >{{ paramValueName }}
          </ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="permissionPath" label="菜单路径" min-width="200"/>
      <ElTableColumn prop="permissionKey" label="权限标识" min-width="180"/>
      <ElTableColumn prop="permissionTopPath" label="父级路由" min-width="140"/>
      <ElTableColumn prop="icon" label="图标" width="100"/>
      <ElTableColumn prop="remarks" label="备注" min-width="200"/>
      <ElTableColumn label="操作" fixed="right" width="220" #default="{ row }">
        <ElButton size="small" @click="e => showDelPop(e, row, `${row.permissionName}`)">
          删除
        </ElButton>
        <ElButton type="primary" size="small" @click="showDialog(row, `-${row.permissionName}`)">编辑</ElButton>
        <ElButton type="primary" size="small" v-if="row.permissionType === 'MENU'" @click="addChild(row)"
                  :plain="row.parentId !== '0'">添加子级
        </ElButton>
      </ElTableColumn>
    </ElTable>
    <!--  删除popover start -->
    <DeletePopover v-if="visibleDelPop" :temp-ref="tempRef" v-model:del-info="delData" v-model="visibleDelPop"
                   @on-submit="del"/>
    <!--  删除popover end -->
    <!-- 添加、编辑 dialog -->
    <DialogMenuPermit ref="dialogRef" v-if="visibleDialog" v-model="visibleDialog"
                      :permission-type-list="permissionTypeList" :menu-list="menuList" @on-close="renderTable"/>
  </TableView>
</template>
